Overload subscript operator [] in C ++
The subscript operator [] in C ++ is often used to access array elements. This operator can be overloaded to enhance existing functionality in arrays in C ++.
The subscript operator [] in C ++ is often used to access array elements. This operator can be overloaded to enhance an existing feature of arrays in C ++ (so it can be called an array index operator).
The following example illustrates how to load the subscript operator [] in C ++:
#include using namespace std ; const int KICHCO = 15 ; class ViDuMang { private : int mang [ KICHCO ]; public : ViDuMang () { register int i ; for ( i = 0 ; i < KICHCO ; i ++) { mang [ i ] = i ; } } int & operator []( int i ) { if ( i > KICHCO ) { cout << "n======================n" << endl ; cout << "Chi muc vuot gioi han!!" << endl ; // Tra ve phan tu dau tien. return mang [ 0 ]; } return mang [ i ]; } }; int main () { ViDuMang V ; cout << "Gia tri cua V[3] la: " << V [ 3 ] << endl ; cout << "Gia tri cua V[6] la: " << V [ 6 ]<< endl ; cout << "Gia tri cua V[16] la: " << V [ 16 ]<< endl ; return 0 ; }
Compiling and running the above C ++ program will produce the following results:
According to Tutorialspoint
Previous article: Load the operator stack call the function () in C ++
Next lesson: Overload member access operator (->) in C ++
You've just finished reading the article "Overload subscript operator [] in C ++" edited by the TipsMake team. You can save overload-subscript-operator-[]-in-c-.pdf to your computer here to read later or print it out. We hope this article has provided you with many useful tech tips and tricks. You can search for similar articles on tips and guides. Thank you for reading and for following us regularly.